package com.atguigu.gmall.common.rabbit.service.impl;

import com.atguigu.gmall.common.rabbit.service.MsgRetryService;
import com.rabbitmq.client.Channel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.DigestUtils;

import java.io.IOException;

public class MsgRetryServiceImpl implements MsgRetryService {

    @Autowired
    private RedisTemplate<String , String> redisTemplate ;

    @Override
    public void msgRetry(String msg, long deliveryTag, Channel channel , int count) {

        // 获取消息的实际消费次数，对实际的消费次数进行+1
        String msgMd5 = DigestUtils.md5DigestAsHex(msg.getBytes());
        String msgRedisKey = "msg:count:" + msgMd5 ;
        Long increment = redisTemplate.opsForValue().increment(msgRedisKey);

        // 判断消息的实际消费次数和最大消费次数之间关系
        if(increment > count) {

            // TODO: 把消息写入到数据库中

            try {

                // 把Redis中的消息的实际消费次数删除掉
                redisTemplate.delete(msgRedisKey) ;

                // 返回ack
                channel.basicAck(deliveryTag , true);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

        }else {

            try {
                // 返回nack
                channel.basicNack(deliveryTag , true , true);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

        }

    }

}
